import type MarkdownIt from "markdown-it";

export default function cardlinkPlugin(md: MarkdownIt) {
	const fence = md.renderer.rules.fence!;

	md.renderer.rules.fence = (tokens, idx, options, env, self) => {
		const token = tokens[idx];

		if (token.info.trim() === "cardlink") {
			const content = token.content.trim();

			const obj = Object.fromEntries(
				content.split("\n").map((line) => {
					const [key, ...rest] = line.split(":");
					return [key.trim(), rest.join(":").trim().replace(/^"|"$/g, "")];
				})
			);

			return `
<Links
  :items="[
    {
      icon: { icon: 'line-md:iconify2-static', color: '#1769AA' },
      size: 48,
      name: '${obj.title}',
      desc: '${obj.description}',
      link: '${obj.url}',
      favicon: '${obj.favicon}'
    }
  ]"
/>
`;
		}

		return fence(tokens, idx, options, env, self);
	};
}
